package com.fzu.express.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fzu.express.entity.Outlet;
import com.fzu.express.entity.WebUser;
import com.fzu.express.enums.RoleEnum;
import com.fzu.express.mapper.OutletMapper;
import com.fzu.express.mapper.WebUserMapper;
import com.fzu.express.pojo.Coordinate;
import com.fzu.express.service.OutletService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fzu.express.service.WebUserService;
import com.fzu.express.utils.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.management.relation.Role;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zyq
 * @since 2022-10-27
 */
@Service
public class OutletServiceImpl extends ServiceImpl<OutletMapper, Outlet> implements OutletService {

    @Resource
    private MapUtil mapUtil;
    @Resource
    private WebUserMapper webUserMapper;

    @Override
    public PageVO listOutlet(Outlet outlet, Integer pageNum, Integer pageSize) {
        Page<Outlet> pageRequest = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<Outlet> wrapper = new LambdaQueryWrapper<>();

        //网点名称
        String name = outlet.getName();
        if (StringUtils.isNotBlank(name)){
            wrapper.eq(Outlet::getName, name);
        }

        //网点负责人
        Long ManagerId = outlet.getManagerId();
        if (ManagerId != null){
            wrapper.eq(Outlet::getManagerId, ManagerId);
        }

        //联系方式
        String phone = outlet.getPhone();
        if (StringUtils.isNotBlank(phone)){
            wrapper.eq(Outlet::getPhone, phone);
        }

        //省份
        String province = outlet.getProvince();
        if (StringUtils.isNotBlank(province)){
            wrapper.eq(Outlet::getProvince, province);
        }

        //城市
        String city = outlet.getCity();
        if (StringUtils.isNotBlank(city)){
            wrapper.eq(Outlet::getCity, city);
        }

        //县区
        String town = outlet.getTown();
        if (StringUtils.isNotBlank(town)){
            wrapper.eq(Outlet::getTown, town);
        }

        //详细地址
        String detailAddress = outlet.getDetailAddress();
        if (StringUtils.isNotBlank(detailAddress)){
            wrapper.eq(Outlet::getDetailAddress, detailAddress);
        }

        //经度
        BigDecimal longitude = outlet.getLongitude();
        if (longitude != null){
            wrapper.eq(Outlet::getLongitude, longitude);
        }

        //纬度
        BigDecimal latitude = outlet.getLatitude();
        if (latitude != null){
            wrapper.eq(Outlet::getLatitude, latitude);
        }

        //状态：1-正常，0-停用
        Integer status = outlet.getStatus();
        if (status != null){
            wrapper.eq(Outlet::getStatus, status);
        }

        //备注信息
        String remark = outlet.getRemark();
        if (StringUtils.isNotBlank(remark)){
            wrapper.eq(Outlet::getRemark, remark);
        }

        //创建时间
        Date createTime = outlet.getCreateTime();
        if (createTime != null){
            wrapper.eq(Outlet::getCreateTime, createTime);
        }

        //更新时间
        Date updateTime = outlet.getUpdateTime();
        if (updateTime != null){
            wrapper.eq(Outlet::getUpdateTime, updateTime);
        }

        //逻辑删除字段：0-正常，1-删除
        Boolean deleted = outlet.getDeleted();
        if (deleted != null){
            wrapper.eq(Outlet::getDeleted, deleted);
        }
        IPage<Outlet> page = super.page(pageRequest, wrapper);

        // 添加网点管理员的信息
        List<Outlet> records = page.getRecords();
        if (!CollectionUtils.isEmpty(records)) {
            List<Long> managerIds = records.stream().filter(e -> e.getManagerId() != null).map(Outlet::getManagerId).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(managerIds)) {
                List<WebUser> webUsers = webUserMapper.selectBatchIds(managerIds);
                Map<Long, WebUser> webUserMap = webUsers.stream().collect(Collectors.toMap(WebUser::getId, Function.identity()));
                for (Outlet record : records) {
                    Long managerId = record.getManagerId();
                    if (managerId != null) {
                        WebUser webUser = webUserMap.get(managerId);
                        record.setManagerName(webUser.getName());
                        record.setManagerPhone(webUser.getPhone());
                        record.setManagerCreateTime(webUser.getCreateTime());
                    }
                }
            }
        }
        return PageVO.convert(page);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addOutlet(Outlet outlet) {
        String province = outlet.getProvince();
        String city = outlet.getCity();
        String town = outlet.getTown();
        String detailAddress = outlet.getDetailAddress();
        if (StringUtils.isBlank(province) || StringUtils.isBlank(city)
            || StringUtils.isBlank(town) || StringUtils.isBlank(detailAddress)) {
            throw new ApiException("请正确填写地址信息");
        }
        // 经纬度生成
        Coordinate coordinate = mapUtil.getCoordinate(province + city + town + detailAddress);
        if (coordinate == null) {
            throw new ApiException("经纬度获取失败，请检查地址信息");
        }
        outlet.setLatitude(BigDecimal.valueOf(coordinate.getLat()));
        outlet.setLongitude(BigDecimal.valueOf(coordinate.getLng()));
        // 网点生成
        super.save(outlet);

        // 网点管理员设置
        WebUser webUser = webUserMapper.selectById(outlet.getManagerId());
        if (webUser == null) {
            throw new ApiException("请选择网点管理员");
        }
        if (!RoleEnum.USER.getCode().equals(webUser.getRole())) {
            throw new ApiException("网点管理员只能为普通用户");
        }
        webUser.setOutletId(outlet.getId());
        webUser.setRole(RoleEnum.OUTLET_MANAGER.getCode());
        webUserMapper.updateById(webUser);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateOutlet(Outlet outlet) {
        Long id = outlet.getId();
        if (id == null){
            throw new ArithmeticException("Id值不能为空");
        }

        Outlet curOutlet = super.getById(id);
        Long managerId = outlet.getManagerId();
        Long curManagerId = curOutlet.getManagerId();
        // 网点管理员发生变化
        if (!managerId.equals(curManagerId)) {
            WebUser manager = webUserMapper.selectById(managerId);
            WebUser curManager = webUserMapper.selectById(curManagerId);
            webUserMapper.updateOutletMangerToUser(curManager.getId());

            manager.setOutletId(id);
            manager.setRole(RoleEnum.OUTLET_MANAGER.getCode());
            webUserMapper.updateById(manager);
        }

        super.updateById(outlet);
    }

    @Override
    public void deleteOutlet(Long id) {
        super.removeById(id);
    }
}
